<?php

//

/**
 * 输出网站核心参数
 *
 * @param        $id
 * @param string $separator 分割符号，有分割符号时返回以为数组
 * @return mixed|string|string[]
 */
function para($id, string $separator = '')
{
	$para = query("para", " paid = '$id' AND paLang = '" . lang . "' ");
	if (empty($id)) {
		$html = "参数ID为空";
	} elseif (empty($para['paid'])) {
		$html = "参数【" . $id . "】未找到";
	} else {
		$html = $para['paValue'];
		if ($separator) {
			$html = array_filter(explode($separator, $para['paValue']));
		}
	}
	return $html;
}

function paraEdit($paid, $para)
{
	update(array(
		"table" => "para",
		"field" => array(
			"paValue" => $para,
			"time"    => date("Y-m-d H:i:s"),
		),
		"where" => " paid = '$paid' AND paLang = '" . lang . "' ",
	));
}

/*所属区域*/
function region($id): string
{
	if (empty($id)) {
		$html = "";
	} else {
		$region = query("region", " id = '$id' ");
		if ($region['id'] != $id) {
			$html = "未找到";
		} else {
			$html = $region['province'] . "-" . $region['city'] . "-" . $region['area'];
		}
	}
	return $html;
}

/*测试记录函数*/
function test($text): string
{
	if (empty($text)) {
		$html = "记录内容为空";
	} else {
		$data = array(
			"table" => "test",
			"field" => array(
				"text" => formSub($text),
				"time" => date("Y-m-d H:i:s"),
			),
		);
		$html = insert($data);
	}
	return $html;
}

/*添加账户记录
$data = array(
    "type" => "账户类型",
    "typeid" => "账户对应目标ID号",
    "direction" => "收入/支出",
    "money" => "发生金额",
    "balance" => "当前余额",
    "text" => "备注",
);
*/
function record($data): string
{
	if (empty($data['type'])) {
		$html = "账户类型为空";
	} elseif (empty($data['typeid'])) {
		$html = "目标ID为空";
	} elseif (empty($data['direction'])) {
		$html = "请选择变动方向";
	} elseif (!in_array($data['direction'], array("收入", "支出"))) {
		$html = "变动方向只能是“收入”或“支出”";
	} elseif (empty($data['money'])) {
		$html = "发生金额为空";
	} elseif (preg_match(checkPrice, $data['money']) == 0) {
		$html = "发生金额格式有误";
	} elseif (preg_match(checkPrice, abs($data['balance'])) == 0) {
		$html = "当前余额格式有误";
	} elseif (empty($data['text'])) {
		$html = "备注为空";
	} else {
		$data['time'] = date("Y-m-d H:i:s");
		$html         = insert(array("table" => "record", "field" => $data));
	}
	return $html;
}

/*待办事项
新增待办事项
$data = array(
    "stid" => "办理人",
    "type" => "类型",
    "typeId" => "待办事项对应表的ID号",
    "text" => "待办事项说明",
    "startDay" => "提示日期",
);
*/
function backlogIn($data): string
{
	if (empty($data['stid'])) {
		$html = "办理人为空";
	} elseif (empty($data['type'])) {
		$html = "类型为空";
	} elseif (empty($data['typeId'])) {
		$html = "目标对象ID为空";
	} elseif (empty($data['text'])) {
		$html = "代办事项说明为空";
	} else {
		if (empty($data['startDay'])) {
			$data['startDay'] = date("Y-m-d");
		}
		$data['id']         = $data['id'] ?? suiji();
		$data['workFlow']   = "待处理";
		$data['updateTime'] = $data['time'] = date("Y-m-d H:i:s");
		$html               = insert(array("table" => "backlog", "field" => $data));
	}
	return $html;
}

/*完成待办事项
$data = array(
    "stid" => "待办事项员工ID号",
    "typeId" => "对象表ID号",
);
*/
function backlogEnd($data)
{
	update(array(
		"table" => "backlog",
		"field" => array(
			"workFlow"   => "已完成",
			"updateTime" => date("Y-m-d H:i:s"),
		),
		"where" => " stid = '$data[stid]' and typeId = '$data[typeId]' and workFlow = '待处理' ", //同一个审核流只可能有一个代办事项处于已完成状态
	));
}

/*消息推送
$data = array(
    "stid" => "被推送人",
    "type" => "类型",
    "typeid" => "消息来源对应表ID号",
    "text" => "消息内容",
);
*/
function message($data): string
{
	if (empty($data['stid'])) {
		$html = "请填写被推送人";
	} elseif (empty($data['type'])) {
		$html = "请填写类型";
	} elseif (empty($data['typeId'])) {
		$html = "请填写消息来源对应表ID号";
	} elseif (empty($data['text'])) {
		$html = "请填写消息内容";
	} else {
		$data['see']     = "否";
		$data['seeTime'] = $data['time'] = date("Y-m-d H:i:s");
		$html            = insert(array("table" => "message", "field" => $data));
	}
	return $html;
}

/*添加审核记录
$data = array(
    "type" => "审批类型",
    "typeId" => "审批对象表ID号",
    "text" => "审核记录",
);
*/
function auditingFollow($data): string
{
	if (empty($data['type'])) {
		$html = "审批类型为空";
	} elseif (empty($data['typeId'])) {
		$html = "审批对象ID为空";
	} elseif (empty($data['text'])) {
		$html = "审核记录为空";
	} else {
		$data['id']   = suiji();
		$data['time'] = date("Y-m-d H:i:s");
		$html         = insert(["table" => "auditing_follow", "field" => $data]);
	}
	return $html;
}


/*签名函数*/
function wxsign($parameter): string
{
	$key = para("wxPayKey"); //key不参与字典排序
	ksort($parameter);       //按照键名对数组升序排序，为数组值保留原来的键。
	//拼接url
	$buff = "";
	foreach ($parameter as $k => $v) {
		$buff .= "$k=$v&";
	}
	$buff .= "key=$key";
	return strtoupper(MD5($buff));
}

/*人力资源管理 - 行政人事 - 职位管理 根据一级导航返回二级导航*/
#[Pure] function getPowerTwo(string $string, string $value = ""): string
{
	$data  = $GLOBALS["powerAll"][$string];
	$power = $data ? array_keys($data) : [];
	return option(array("title" => "二级导航", "option" => $power, "value" => $value));
}

/*人力资源管理 - 行政人事 - 职位管理 根据二级导航返回三级导航*/
function getPowerThree(string $string, string $value = "", string $field = 'name'): string
{
	$keys  = explode('-', $string);
	$power = [];
	if (count($keys) == 2) {
		$data = $GLOBALS["powerAll"][$keys[0]][$keys[1]];
		unset($data['folder']);
		unset($data['mIco']);
		foreach ($data as $type => $module) {
			if (array_key_exists($field, $module)) {
				$power[$type] = $module['name'];
			}
		}
	}
	return option(array("title" => "三级导航", "option" => $power, "value" => $value));
}

/*多条件模糊查询**
$data = array(
    "like" => "模糊查询",
    "=" => "全等查询",
    ">=" => "大于等于查询",
    "<=" => "小于等于查询",
    "in" => "包含查询，必须为数组",
);
*/
function search($data): string
{
	$sql = "";
	foreach ($data as $name => $array) {
		foreach ($array as $key => $value) {
			if ($name == "in" and is_array($value) and count($value) > 0) {
				$sql .= " and " . $key . " in ('" . implode("','", $value) . "') ";
			} elseif (in_array($name, ["like", "=", ">=", "<=", ">", "<"]) and mb_strlen($value, "utf8") > 0) {
				if ($name == "like") {
					$value = "%$value%";
				}
				$sql .= " and " . $key . " " . $name . " '" . $value . "' ";
			}
		}
	}
	return $sql;
}

function searchRegion($province, $city, $area): string
{
	$sql = '';
	if (isset($province)) {
		if (empty($city)) {
			$sql = " and regionId in ( select id from region where province = '$province' ) ";
		} else {
			if (empty($area)) {
				$sql = " and regionId in ( select id from region where province = '$province' and city = '$city' ) ";
			} else {
				$sql = " and regionId = '$area' ";
			}
		}
	}
	return $sql;
}

function searchStaffId($department, $jobId, $staffId): string
{
	if (empty($department)) {
		$and = "";
	} else {
		if (empty($jobId)) {
			$and = " and jobId in ( select id from job where department = '$department' ) ";
		} else {
			if (empty($staffId)) {
				$and = " and jobId = '$jobId' ";
			} else {
				$and = " and stid = '$staffId' ";
			}
		}
	}
	return $and;
}

/*打印文章明细*/
function articleMx($id): string
{
	$article = "";
	$sql     = find(array("table" => "article", "field" => "img,word", "where" => "typeId = '$id' order by list"));
	foreach ($sql['array'] as $array) {
		if (empty($array['img'])) {
			$article .= neirong($array['word']);
		} else {
			$article .= "<div class='center'><img src='" . root . $array['img'] . "' alt='文章图片'></div>";
		}
	}
	return $article;
}

/**
 * 消息提示
 *
 * @param string $msg
 * @return string
 */
function msg(string $msg = ""): string
{
	$html = '';
	if (isset($_SESSION['msg'])) {
		$msg = $_SESSION['msg']; //接收session中的提示信息
		unset($_SESSION['msg']);
	} elseif (isset($GLOBALS['msg'])) { //接收全局变量中的提示信息
		$msg = $GLOBALS['msg'];
	}
	if (isset($msg) && $msg) {
		$html = "<script>msg('$msg')</script>";
	}
	return $html;
}

/*网站头部*/
function head($type, $title = ""): string
{
	$meta    = $automatic = $css = $js = '';
	$root    = root;
	$version = version;
	if ($type == "ad") {
		$css = <<<EOT
	<link href="{$root}static/stylesheet/animate.min.css?v=$version" rel="stylesheet">
	<link href="{$root}static/stylesheet/css.css?v=$version" rel="stylesheet">
	<link href="{$root}static/stylesheet/workflow.css?v=$version" rel="stylesheet">
	<link href="{$root}static/stylesheet/cxdialog.css?v=$version" rel="stylesheet">
EOT;
		$js  = <<<EOT
	<script src="{$root}static/javascript/js.js?v=$version"></script>
	<script src="{$root}static/javascript/fixedThead.js?v=$version"></script>
	<script src="{$root}static/javascript/jquery.ztree.all.js?v=$version"></script>
	<script src="{$root}static/javascript/workflow.js?v=$version"></script>
	<script src="{$root}static/javascript/popper.min.js?v=$version"></script>
	<script src="{$root}static/javascript/tippy.js?v=$version"></script>
	<script src="{$root}static/javascript/jquery.bigautocomplete.js?v=$version"></script>
	<script src="{$root}static/javascript/cxdialog.js?v=$version"></script>
	<script src="{$root}static/javascript/crypto-js.min.js?v=$version"></script>
EOT;
	} elseif ($type == "report") {
		$css = <<<EOT
	<link href="{$root}static/stylesheet/animate.min.css?v=$version" rel="stylesheet">
	<link href="{$root}static/stylesheet/report.css?v=$version" rel="stylesheet">
	<link href="{$root}static/stylesheet/cxdialog.css?v=$version" rel="stylesheet">
EOT;
		$js  = <<<EOT
	<script src="{$root}static/javascript/js.js?v=$version"></script>
	<script src="{$root}static/javascript/jquery.ztree.all.min.js?v=$version"></script>
	<script src="{$root}static/javascript/popper.min.js?v=$version"></script>
	<script src="{$root}static/javascript/jquery.bigautocomplete.js?v=$version"></script>
	<script src="{$root}static/javascript/cxdialog.js?v=$version"></script>
EOT;
	} elseif ($type == "pc") {
		$css = <<<EOT
	<link href="{$root}static/stylesheet/pc.css?v=$version" rel="stylesheet">
EOT;
		$js  = <<<EOT
	<script src="{$root}static/javascript/pc.js?v=$version"></script>
EOT;
	} elseif ($type == "m") {
		$css  = <<<EOT
	<link href="{$root}static/stylesheet/m.css?v=$version" rel="stylesheet">
EOT;
		$js   = <<<EOT
	<script src="{$root}static/javascript/m.js?v=$version"></script>
EOT;
		$meta = "
	<meta name='viewport' content='width=device-width,initial-scale=1.0,minimum-scale=0.5,maximum-scale=2.0,user-scalable=yes'>
	<meta name='apple-mobile-web-app-capable' content='yes'>
	<meta name='apple-mobile-web-app-status-bar-style' content='black'>
	<meta name='format-detection' content='telephone=no,email=no,adress=no'>
		";
	}
	if (empty($title)) {
		$title = para("title");
	}
	if (para("automatic") != date("Ymd")) {
		$automatic = "
		$(function(){
			$.post(root+'library/libData.html?type=automatic');
		});";
	}
	
	$settingInfo     = query('option_setting', "type = '公共'");
	$amountPrecision = 2;
	$keywords        = para("keywords");
	$description     = para("description");
	return <<<EOT
<!DOCTYPE html>
<html lang="zh-CN">
<head>
	<meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="edge">
	<meta name="keywords" content="$keywords">
	<meta name="description" content="$description">
	<title>$title</title>
$meta $css
	<link href="{$root}favicon.ico?v=$version" rel="Bookmark">
	<link href="{$root}favicon.ico?v=$version" rel="icon">
	<link href="{$root}favicon.ico?v=$version" rel="shortcut icon">
	<link href="{$root}favicon.ico?v=$version" rel="apple-touch-icon">
	<script src="{$root}static/javascript/jquery-1.11.2.min.js?v=$version"></script>
	<script src="{$root}static/javascript/lib.js?v=$version"></script>
	<script src="{$root}static/plugins/laydate/laydate.js?v=$version"></script>
$js
	<script>
	let root = '$root';
	const publicSettings =$.parseJSON('{$settingInfo["setting"]}');
	let amountPrecision = '$amountPrecision';
	$automatic
	</script>
</head>
<body>
EOT;
}


/*获取当前星期几的函数*/
function week($timeStamp = ""): string
{
	if (empty($timeStamp)) {
		$n = date("N");
	} else {
		$n = date("N", $timeStamp);
	}
	if ($n == 1) {
		$week = "星期一";
	} elseif ($n == 2) {
		$week = "星期二";
	} elseif ($n == 3) {
		$week = "星期三";
	} elseif ($n == 4) {
		$week = "星期四";
	} elseif ($n == 5) {
		$week = "星期五";
	} elseif ($n == 6) {
		$week = "星期六";
	} elseif ($n == 7) {
		$week = "星期天";
	} else {
		$week = "异常";
	}
	return $week;
}

/*文章点击量*/
function contentClickRate($id)
{
	$content = query("content", " id = '$id' ");
	if (!in_array($id, (array)$_SESSION['clickRate'])) {
		$_SESSION['clickRate'][] = $id;
		update(array(
			"table" => "content",
			"field" => array(
				"clickRate" => $content['clickRate'] + 1,
			),
			"where" => "id = '$id'",
		));
	}
}


/*串联get参数*/
function get($get)
{
	$html = "";
	if (count($get) > 0) {
		foreach ($get as $key => $value) {
			if (empty($html)) {
				$html = "?";
			} else {
				$html .= "&";
			}
			$html .= $key . "=" . $value;
		}
	}
	return $html;
}

function lang($key)
{
	$language = langLocales();
	$res      = explode('.', $key);
	$value    = $language;
	foreach ($res as $v) {
		$value = $value[$v];
	}
	return $value;
}

function getLang()
{
	if (!empty($_SESSION['lang'])) {
		return $_SESSION['lang'];
	}
	if (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
		$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 5);
		// 简体
		if (preg_match('/zh-cn/i', $lang)) {
			$lang = 'SC';
		} // 繁体
		elseif (preg_match('/zh/i', $lang)) {
			$lang = 'TC';
		} // 英语
		else {
			$lang = 'EN';
		}
		$_SESSION['lang'] = $lang;
		return $lang;
	} else {
		$_SESSION['lang'] = 'SC';
		return 'SC';
	}
}

function langLocales()
{
	$locales = match (lang) {
		'TC'    => 'zh_HK.php',
		'EN'    => 'en.php',
		default => 'zh_CN.php',
	};
	return require serverRoot . 'lang/' . $locales;
}

function langReplace($matches)
{
	$temp = str_replace(['{l.', '}'], '', $matches[0]);
	return str_replace($temp, lang($temp), $temp);
}

/**
 * 获取指定key 的多语言
 *
 * @param $key
 * @return mixed
 */
function L($key)
{
	return lang($key);
}
